#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "DynamicArray.h"

struct Student
{
    char *name;
    int age;
};
typedef struct Student Stu;

Stu* CreateStu(const char *name, int age)
{
    Stu *s = (Stu*)malloc(sizeof(Stu));
    if(s == NULL)
    {
        printf("student malloc error!\n");
        return NULL;
    }
    s->name = strdup(name);
    s->age = age;
    return s;
}

//销毁
void FreeStu(void *ptr)
{
    Stu *s = (Stu *)ptr;
    free(s->name);
    free(s);
}

//显示
void PrintStu(void *ptr)
{
    Stu *s = (Stu *)ptr;
    printf("学生姓名：%s 年龄：%d\n", s->name, s->age);
}


bool SortByAge(void *ptr1, void *ptr2)
{
    Stu *s1 = (Stu *)ptr1;
    Stu *s2 = (Stu *)ptr2;

    return s1->age > s2->age;
}

bool SortByName(void *ptr1, void *ptr2)
{
    Stu *s1 = (Stu *)ptr1;
    Stu *s2 = (Stu *)ptr2;

    return strcmp(s1->name, s2->name) > 0;
}

int SearchByName(void *ptr1, void *ptr2)
{
    Stu *s1 = (Stu *)ptr1;
    char *name = (char *)ptr2;
    return strcmp(s1->name, name);
}

int main()
{
    DArray *a = InitDArray(10, FreeStu);
    InsertTail(a, CreateStu("zhangsan", 20));
    InsertTail(a, CreateStu("lisi", 21));
    InsertTail(a, CreateStu("wangwu", 19));

    DArrayFastSort(a, SortByName);
    PrintArray(a, PrintStu);

    ElementType ptr = BinarySearch(a, "zhaoliu", SearchByName);
    if(ptr == NULL)
    {
        printf("没找到！\n");
    }
    else
    {
        PrintStu(ptr);
    }

    FreeDArray(a);
    return 0;
}